﻿using System;
using Hadlow.Jobvertizer.Models;
using Castle.ActiveRecord.Queries;

namespace Hadlow.Jobvertizer.Repositories
{
    public class PosterRepository : Repository<Poster>, IPosterRepository
    {
        public Poster GetPosterFor(User user)
        {
            if (user.Role != Role.Poster)
                throw new ApplicationException("User must have the role 'Poster'");

            SimpleQuery<Poster> posterByUserQuery = new SimpleQuery<Poster>(
                @"select p
                from Poster p 
                join p.PosterUsers pu
                where pu.User = ?",
                user);

            Poster[] posters = posterByUserQuery.Execute();
            if (posters.Length == 0)
                throw new ApplicationException(string.Format("No Poster found for User {0}", user));
            if (posters.Length > 1)
                throw new ApplicationException(string.Format("Multiple Posters found for User {0}", user));

            return posters[0];
        }
    }
}
